package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasCaminfoForecastEntity;
import cn.com.gas.entity.GasMineExportEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStationinfoForecastEntity;
import cn.com.gas.service.GasCaminfoForecastService;
import cn.com.gas.service.GasMineExportService;
import cn.com.gas.service.GasStationinfoForecastService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.vo.excel.GasStationinfoForecastExcel;
import cn.com.system.entity.SysDept;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.DeptService;
import cn.com.system.service.SysParameterService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 加油站预估列表
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-07-10 10:26:01
 */
@Controller
@RequestMapping("/gas/stationforecast")
public class GasStationinfoForecastController {

	@Autowired
	private GasStationinfoForecastService gasStationinfoForecastService;
	@Autowired
	private GasCaminfoForecastService gasCaminfoForecastService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	
	@Autowired
	private GasMineExportService gasMineExportService;
	
	@Autowired
	private DeptService deptService;

	@Autowired
	private SysParameterService sysParameterService;

	@Autowired
	private HttpSessionService httpSessionService;
	
	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "取流异常预警列表")
	@PostMapping("/forewarningStreamList")
	// @RequiresPermissions("gasStationinfoForecast:list")
	@ResponseBody
	public DataResult forewarningStreamList(@RequestBody GasStationinfoForecastEntity stationinfoForecast)
			throws ParseException {

		SysParameterEntity parameter104 = sysParameterService.getById("parameter104");

		String offlineTime = "1800"; // 秒
		if (TsBqUtils.isNotNull(parameter104)) {
			offlineTime = parameter104.getParameter();
		}
		
		/*BigDecimal a = new BigDecimal(offlineTime);
	    BigDecimal b = new BigDecimal("60");
	        
        BigDecimal offlineTimeBd = a.multiply(b);
        offlineTime = offlineTimeBd.toString();*/
		
		
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String currentDeptId = httpSessionService.getCurrentDeptId();

		String taxorgcode = stationinfoForecast.getTaxorgcode();
		LambdaQueryWrapper<GasStationinfoEntity> stationinfoQueryWrapper = Wrappers.lambdaQuery();

		if (TsBqUtils.isNotNull(taxorgcode)) {
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				stationinfoQueryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
				stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

			}
		}
		if(TsBqUtils.isNotNull(stationinfoForecast.getStationinfoName())){
			stationinfoQueryWrapper.like(GasStationinfoEntity::getName, stationinfoForecast.getStationinfoName());
		}
		List<GasStationinfoEntity> stationinfoList = gasStationinfoService.list(stationinfoQueryWrapper);
		List<String> listStationId = new ArrayList<>();
		for (GasStationinfoEntity stationinfo : stationinfoList) {
			String id = stationinfo.getId();
			listStationId.add(id);
		}

		Page page = new Page(stationinfoForecast.getPage(), stationinfoForecast.getLimit());

		LambdaQueryWrapper<GasCaminfoForecastEntity> queryWrapper = Wrappers.lambdaQuery();

		queryWrapper.ge(GasCaminfoForecastEntity::getOfflineTime, Integer.parseInt(offlineTime)); // 单位秒

		queryWrapper.in(GasCaminfoForecastEntity::getStationinfoId, listStationId);

		if (!StringUtils.isEmpty(stationinfoForecast.getCreateTimeStart())) {
			
			/*queryWrapper.ge(GasCaminfoForecastEntity::getCreateTime,
					sdf.parse(stationinfoForecast.getCreateTimeStart() + " 00:00:00"));*/
			queryWrapper.ge(GasCaminfoForecastEntity::getTime,
					stationinfoForecast.getCreateTimeStart().trim());
			
		}
		
		if (!StringUtils.isEmpty(stationinfoForecast.getCreateTimeEnd())) {
			
			/*queryWrapper.le(GasCaminfoForecastEntity::getCreateTime,
					sdf.parse(stationinfoForecast.getCreateTimeEnd() + " 23:59:59"));*/
			queryWrapper.le(GasCaminfoForecastEntity::getTime,
					stationinfoForecast.getCreateTimeEnd().trim());
			
		}
		

		IPage<GasCaminfoForecastEntity> iPage = gasCaminfoForecastService.page(page, queryWrapper);

		List<GasCaminfoForecastEntity> records = iPage.getRecords();
		for (GasCaminfoForecastEntity gasStationinfo : records) {
			String stationinfoId = gasStationinfo.getStationinfoId();
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(stationinfoId);
			SysDept dept = deptService.getById(stationinfo.getTaxorgcode());
			String deptName = "";
			if (TsBqUtils.isNotNull(dept)) {
				deptName = dept.getName();
			} else {
				deptName = stationinfo.getTaxorgcode();
			}
			String name = stationinfo.getName();
			gasStationinfo.setStationinfoName(TsBqUtils.handleEndBeforeParentheses(name));

			gasStationinfo.setTaxorgname(deptName);

		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "油站站预估0级-加油站信息")
	@PostMapping("/list3")
	// @RequiresPermissions("gasStationinfoForecast:list")
	@ResponseBody
	public DataResult list3(@RequestBody GasStationinfoForecastEntity gasStationinfoForecast) throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		
		String taxpayerCode = gasStationinfoForecast.getTaxpayerCode();
		String taxorgcode = gasStationinfoForecast.getTaxorgcode();

		String currentDeptId = httpSessionService.getCurrentDeptId();

		Page page = new Page(gasStationinfoForecast.getPage(), gasStationinfoForecast.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

		if (TsBqUtils.isNotNull(taxorgcode)) {
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

			}
		}

		if (TsBqUtils.isNotNull(gasStationinfoForecast.getStationinfoName())) {
			queryWrapper.like(GasStationinfoEntity::getName, gasStationinfoForecast.getStationinfoName());
		}
		
		if (TsBqUtils.isNotNull(taxpayerCode)) {
			queryWrapper.like(GasStationinfoEntity::getTaxpayerCode, taxpayerCode);
		}
		
		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);

		List<GasStationinfoEntity> records = iPage.getRecords();
		for (GasStationinfoEntity gasStationinfoEntity : records) {
			// 处理加油站 名称
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
			}
			// 税务机关
			if (TsBqUtils.isNotNull(gasStationinfoEntity.getTaxorgcode())) {
				SysDept sysDept = deptService.getById(gasStationinfoEntity.getTaxorgcode());
				gasStationinfoEntity.setTaxorgName(sysDept.getName());
			}

			// 计算累计金额
			BigDecimal gatherValueDecimal = new BigDecimal(0);
			BigDecimal forecastValueDecimal = new BigDecimal(0);
			BigDecimal offlineDecimal = new BigDecimal(0);
			
			
			String id = gasStationinfoEntity.getId();

			LambdaQueryWrapper<GasCaminfoForecastEntity> queryWrapper1 = Wrappers.lambdaQuery();
			queryWrapper1.eq(GasCaminfoForecastEntity::getStationinfoId, id);

			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeStart())) {
				/*queryWrapper1.ge(GasCaminfoForecastEntity::getCreateTime,
						sdf.parse(gasStationinfoForecast.getCreateTimeStart() + " 00:00:00"));*/
				queryWrapper1.ge(GasCaminfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeStart().trim());
			
			}
			
			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeEnd())) {
				/*queryWrapper1.le(GasCaminfoForecastEntity::getCreateTime,
						sdf.parse(gasStationinfoForecast.getCreateTimeEnd() + " 23:59:59"));*/
				queryWrapper1.le(GasCaminfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeEnd().trim());
				
			}

			List<GasCaminfoForecastEntity> list = gasCaminfoForecastService.list(queryWrapper1);

			String gasLocation = gasStationinfoEntity.getGasLocation();
			String gasCoverage = gasStationinfoEntity.getGasCoverage();

			for (GasCaminfoForecastEntity caminfoForecast : list) {
				String gatherValue = caminfoForecast.getGatherValue();
				BigDecimal _gatherValue = new BigDecimal(gatherValue);
				gatherValueDecimal = gatherValueDecimal.add(_gatherValue);

				String forecastValue = caminfoForecast.getForecastValue();
				BigDecimal _forecastValue = new BigDecimal(forecastValue);
				forecastValueDecimal = forecastValueDecimal.add(_forecastValue);

				String offlineTime = caminfoForecast.getOfflineTime();

				BigDecimal _offlineDecimal = new BigDecimal(offlineTime);
				offlineDecimal = offlineDecimal.add(_offlineDecimal);
				
				
			}

			if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
					&& !"0".equals(gasLocation)) {

				BigDecimal divide = forecastValueDecimal.divide(new BigDecimal(gasCoverage), 2,
						BigDecimal.ROUND_HALF_UP);
				forecastValueDecimal = divide.multiply(new BigDecimal(gasLocation));

			}

			gasStationinfoEntity.setGatherValue(gatherValueDecimal.toString());
			gasStationinfoEntity.setForecastValue(forecastValueDecimal.toString());

			if (offlineDecimal.compareTo(BigDecimal.ZERO) == 0 && gatherValueDecimal.compareTo(BigDecimal.ZERO) == 0 ) {
				Date parseStart = sdf.parse(gasStationinfoForecast.getCreateTimeStart() + " 00:00:00");
				Date parseEnd = sdf.parse(gasStationinfoForecast.getCreateTimeEnd() + " 23:59:59");

				int result = date.compareTo(parseEnd);
				int daysBetween = 0;
				
				boolean equals = gasStationinfoForecast.getCreateTimeStart().trim().equals(gasStationinfoForecast.getCreateTimeEnd().trim());
				if(!equals){
					if (result < 0) {
						// date 早
						daysBetween = daysBetween(parseStart, date);
					} else if (result > 0) {
						// date 晚
						daysBetween = daysBetween(parseStart, parseEnd);
					} else {
						// 
						daysBetween = 1;
					}
				}else{
					daysBetween = 1;
				}
				
				gasStationinfoEntity.setOfflineTime(String.valueOf(daysBetween * 24 * 60 * 60).replace("-", ""));

			} else {
				gasStationinfoEntity.setOfflineTime(offlineDecimal.toString());
			}
			
			// 计算  forecastValue1 gasLocation1 gasCoverage1 
			LambdaQueryWrapper<GasStationinfoForecastEntity> queryWrapper2 = Wrappers.lambdaQuery();
			queryWrapper2.eq(GasStationinfoForecastEntity::getStationinfoId, id);

			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeStart())) {
				queryWrapper2.ge(GasStationinfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeStart().trim());
			
			}
			
			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeEnd())) {
				queryWrapper2.le(GasStationinfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeEnd().trim());
				
			}

			List<GasStationinfoForecastEntity> list1 = gasStationinfoForecastService.list(queryWrapper2);
			if(TsBqUtils.isNotNull(list1)){
				
				BigDecimal forecastValueDecimal1 = new BigDecimal(0);
				BigDecimal amountDecimal = new BigDecimal(0);
				
				for (GasStationinfoForecastEntity _gasStationinfoForecast : list1) {
					String forecast = "0";
					String forecastValue1 = _gasStationinfoForecast.getForecastValue1();
					String forecastValue = _gasStationinfoForecast.getForecastValue();
					
					
					
					if(TsBqUtils.isNotNull(forecastValue1)){
						forecast = forecastValue1;
					}else if(TsBqUtils.isNotNull(forecastValue)){
						
						if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
								&& !"0".equals(gasLocation)) {
							BigDecimal forecastValueBd = new BigDecimal(forecastValue);
							
							BigDecimal divide = forecastValueBd.divide(new BigDecimal(gasCoverage), 2,
									BigDecimal.ROUND_HALF_UP);
							forecastValueDecimal = divide.multiply(new BigDecimal(gasLocation));
							
							forecast = forecastValueDecimal.toString();

						}else{
							forecast = forecastValue;
							
						}
						
					}
					
					BigDecimal _forecastValue = new BigDecimal(forecast);
					forecastValueDecimal1 = forecastValueDecimal1.add(_forecastValue);
					
					
					String amountDiesel = _gasStationinfoForecast.getAmountDiesel();
					String amountGasoline = _gasStationinfoForecast.getAmountGasoline();
					if(TsBqUtils.isNotNull(amountDiesel)){
						BigDecimal _amountDecimal = new BigDecimal(amountDiesel);
						amountDecimal = amountDecimal.add(_amountDecimal);
					}
					
					if(TsBqUtils.isNotNull(amountGasoline)){
						BigDecimal _amountDecimal = new BigDecimal(amountGasoline);
						amountDecimal = amountDecimal.add(_amountDecimal);
					}
					
				}
				
				gasStationinfoEntity.setForecastValue1(forecastValueDecimal1.toString());
				gasStationinfoEntity.setAmount(amountDecimal.toString());
			}
						
		}

		return DataResult.success(iPage);

	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "油站站预估1级-加油站信息")
	@PostMapping("/list2")
	// @RequiresPermissions("gasStationinfoForecast:list")
	@ResponseBody
	public DataResult list2(@RequestBody GasStationinfoForecastEntity gasStationinfoForecast) throws ParseException {

		String currentDeptId = httpSessionService.getCurrentDeptId();
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String stationinfoName = gasStationinfoForecast.getStationinfoName();

		String deptId = gasStationinfoForecast.getTaxorgcode();
		// 查询加油站
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, deptId);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局 
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else{
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationinfoName)) {
			queryWrapperStationinfo.like(GasStationinfoEntity::getName, stationinfoName);
		}
		List<GasStationinfoEntity> listGasStationinfo = gasStationinfoService.list(queryWrapperStationinfo);
		List<String> stationinfoIdList = new ArrayList<>();
		for (GasStationinfoEntity stationinfo : listGasStationinfo) {
			String stationinfoId = stationinfo.getId();
			stationinfoIdList.add(stationinfoId);
		}

		Page page = new Page(gasStationinfoForecast.getPage(), gasStationinfoForecast.getLimit());
		LambdaQueryWrapper<GasStationinfoForecastEntity> queryWrapper = Wrappers.lambdaQuery();

		// 查询条件示例
		if (TsBqUtils.isNotNull(gasStationinfoForecast.getStationinfoId())) {
			queryWrapper.eq(GasStationinfoForecastEntity::getStationinfoId, gasStationinfoForecast.getStationinfoId());
		}

		if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeStart())) {
			/*queryWrapper.ge(GasStationinfoForecastEntity::getCreateTime,
					sdf.parse(gasStationinfoForecast.getCreateTimeStart() + " 00:00:00"));*/
			queryWrapper.ge(GasStationinfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeStart().trim());

			
		}
		
		if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeEnd())) {
			/*queryWrapper.le(GasStationinfoForecastEntity::getCreateTime,
					sdf.parse(gasStationinfoForecast.getCreateTimeEnd() + " 23:59:59"));*/
			queryWrapper.le(GasStationinfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeEnd().trim());

		}
		
		queryWrapper.orderByDesc(GasStationinfoForecastEntity::getTime);

		IPage<GasStationinfoForecastEntity> iPage = gasStationinfoForecastService.page(page, queryWrapper);
		List<GasStationinfoForecastEntity> records = iPage.getRecords();
		for (GasStationinfoForecastEntity stationinfoForecast : records) {
			
			// 设置加工的获取加油区
			stationinfoForecast.setGasLocation1(stationinfoForecast.getGasLocation());
			stationinfoForecast.setGasCoverage1(stationinfoForecast.getGasCoverage());
						
			String stationinfoId = stationinfoForecast.getStationinfoId();
			String taxorgcode = stationinfoForecast.getTaxorgcode();
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(stationinfoId);

			String gasLocation = stationinfo.getGasLocation();
			String gasCoverage = stationinfo.getGasCoverage();
			
			stationinfoForecast.setGasLocation(gasLocation);
			stationinfoForecast.setGasCoverage(gasCoverage);

			SysDept sysDept = deptService.getById(taxorgcode);
			String taxName = taxorgcode;
			if (TsBqUtils.isNotNull(sysDept)) {
				taxName = sysDept.getName();
			}

			stationinfoForecast.setStationinfoName(TsBqUtils.handleEndBeforeParentheses(stationinfo.getName()));
			stationinfoForecast.setTaxorgName(taxName);

			String forecastValue = stationinfoForecast.getForecastValue();

			if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
					&& !"0".equals(gasLocation)){
			
				BigDecimal _forecastValue = new BigDecimal(forecastValue);
				BigDecimal divide = _forecastValue.divide(new BigDecimal(gasCoverage), 2, BigDecimal.ROUND_HALF_UP);
				BigDecimal multiply = divide.multiply(new BigDecimal(gasLocation));
				stationinfoForecast.setForecastValue(multiply.toString());
				
			} else {
				stationinfoForecast.setForecastValue(forecastValue);
			}
		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "油站站预估2级-摄像头信息")
	@PostMapping("/list1")
	// @RequiresPermissions("gasStationinfoForecast:list")
	@ResponseBody
	public DataResult list1(@RequestBody GasCaminfoForecastEntity gasStationinfoForecast) {

		Page page = new Page(gasStationinfoForecast.getPage(), gasStationinfoForecast.getLimit());
		LambdaQueryWrapper<GasCaminfoForecastEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		queryWrapper.eq(GasCaminfoForecastEntity::getStationinfoId, gasStationinfoForecast.getStationinfoId());
		queryWrapper.eq(GasCaminfoForecastEntity::getTime, gasStationinfoForecast.getTime());
		queryWrapper.orderByDesc(GasCaminfoForecastEntity::getStationinfoId);
		IPage<GasCaminfoForecastEntity> iPage = gasCaminfoForecastService.page(page, queryWrapper);

		List<GasCaminfoForecastEntity> records = iPage.getRecords();
		for (GasCaminfoForecastEntity caminfoForecast : records) {

			String camid = caminfoForecast.getCamId();
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(camid);

			caminfoForecast.setCamName(stationinfo.getName());

		}

		return DataResult.success(iPage);

	}
	
	@PostMapping("/exportData")
	@ResponseBody
	public DataResult exportData(@RequestBody GasStationinfoForecastEntity gasStationinfoForecast)
			throws java.io.IOException, ParseException {
				
		String currentDeptId = httpSessionService.getCurrentDeptId();
		String currentUserId = httpSessionService.getCurrentUserId();

		// 插入gas_mine_export表
		GasMineExportEntity mineExportEntity = new GasMineExportEntity();
		String uuid = TsBqUtils.getUUID();
		mineExportEntity.setId(uuid);
		mineExportEntity.setModule("加油站预估");

		mineExportEntity.setDeleted(Constants.DATA_NOT_DELETED);
		mineExportEntity.setCreateTime(new Date());
		mineExportEntity.setCreateId(currentUserId);
		mineExportEntity.setCreateTaxorgcode(currentDeptId);

		gasMineExportService.save(mineExportEntity);
		
		new Thread(() -> {
			try {
				System.out.println("睡眠前");
				Thread.sleep(20000);// 休眠时间设置为10000毫秒（10秒）
				System.out.println("睡眠后");
				asynExportData(gasStationinfoForecast, uuid, currentDeptId);

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}).start();

		return DataResult.success("稍后请在【我的导出】进行下载导出内容！");
	
	}
	
	
	private void asynExportData(GasStationinfoForecastEntity gasStationinfoForecast, String uuid, String currentDeptId) throws ParseException {
		GasMineExportEntity gasMineExportEntity = gasMineExportService.getById(uuid);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();

		String taxorgcode = gasStationinfoForecast.getTaxorgcode();
		
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

		if (TsBqUtils.isNotNull(taxorgcode)) {
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

			}
		}

		if (TsBqUtils.isNotNull(gasStationinfoForecast.getStationinfoName())) {
			queryWrapper.like(GasStationinfoEntity::getName, gasStationinfoForecast.getStationinfoName());
		}
		
		if (TsBqUtils.isNotNull(gasStationinfoForecast.getTaxpayerCode())) {
			queryWrapper.like(GasStationinfoEntity::getTaxpayerCode, gasStationinfoForecast.getTaxpayerCode());
		}
		
		List<GasStationinfoEntity> records = gasStationinfoService.list(queryWrapper);

		for (GasStationinfoEntity gasStationinfoEntity : records) {
			// 处理加油站 名称
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
			}
			// 税务机关
			if (TsBqUtils.isNotNull(gasStationinfoEntity.getTaxorgcode())) {
				SysDept sysDept = deptService.getById(gasStationinfoEntity.getTaxorgcode());
				gasStationinfoEntity.setTaxorgName(sysDept.getName());
				
			}

			// 计算累计金额
			BigDecimal gatherValueDecimal = new BigDecimal(0);
			BigDecimal forecastValueDecimal = new BigDecimal(0);
			BigDecimal offlineDecimal = new BigDecimal(0);

			String id = gasStationinfoEntity.getId();

			LambdaQueryWrapper<GasCaminfoForecastEntity> queryWrapper1 = Wrappers.lambdaQuery();
			queryWrapper1.eq(GasCaminfoForecastEntity::getStationinfoId, id);

			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeStart())) {
				queryWrapper1.ge(GasCaminfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeStart().trim());
			
			}
			
			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeEnd())) {
				queryWrapper1.le(GasCaminfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeEnd().trim());
				
			}

			List<GasCaminfoForecastEntity> list = gasCaminfoForecastService.list(queryWrapper1);

			String gasLocation = gasStationinfoEntity.getGasLocation();
			String gasCoverage = gasStationinfoEntity.getGasCoverage();

			for (GasCaminfoForecastEntity caminfoForecast : list) {
				String gatherValue = caminfoForecast.getGatherValue();
				BigDecimal _gatherValue = new BigDecimal(gatherValue);
				gatherValueDecimal = gatherValueDecimal.add(_gatherValue);

				String forecastValue = caminfoForecast.getForecastValue();
				BigDecimal _forecastValue = new BigDecimal(forecastValue);
				forecastValueDecimal = forecastValueDecimal.add(_forecastValue);

				String offlineTime = caminfoForecast.getOfflineTime();

				BigDecimal _offlineDecimal = new BigDecimal(offlineTime);
				offlineDecimal = offlineDecimal.add(_offlineDecimal);

			}

			if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
					&& !"0".equals(gasLocation)) {

				BigDecimal divide = forecastValueDecimal.divide(new BigDecimal(gasCoverage), 2,
						BigDecimal.ROUND_HALF_UP);
				forecastValueDecimal = divide.multiply(new BigDecimal(gasLocation));

			}

			gasStationinfoEntity.setGatherValue(gatherValueDecimal.toString());
			gasStationinfoEntity.setForecastValue(forecastValueDecimal.toString());

			if (offlineDecimal.compareTo(BigDecimal.ZERO) == 0 && gatherValueDecimal.compareTo(BigDecimal.ZERO) == 0 ) {
				Date parseStart = sdf.parse(gasStationinfoForecast.getCreateTimeStart() + " 00:00:00");
				Date parseEnd = sdf.parse(gasStationinfoForecast.getCreateTimeEnd() + " 23:59:59");

				int result = date.compareTo(parseEnd);
				int daysBetween = 0;
				
				boolean equals = gasStationinfoForecast.getCreateTimeStart().trim().equals(gasStationinfoForecast.getCreateTimeEnd().trim());
				if(!equals){
					if (result < 0) {
						// date 早
						daysBetween = daysBetween(parseStart, date);
					} else if (result > 0) {
						// date 晚
						daysBetween = daysBetween(parseStart, parseEnd);
					} else {
						// 
						daysBetween = 1;
					}
				}else{
					daysBetween = 1;
				}
				
				gasStationinfoEntity.setOfflineTime(String.valueOf(daysBetween * 24 * 60 * 60).replace("-", ""));

			} else {
				gasStationinfoEntity.setOfflineTime(offlineDecimal.toString());
			}
			
			// 计算  forecastValue1 gasLocation1 gasCoverage1
			LambdaQueryWrapper<GasStationinfoForecastEntity> queryWrapper2 = Wrappers.lambdaQuery();
			queryWrapper2.eq(GasStationinfoForecastEntity::getStationinfoId, id);

			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeStart())) {
				queryWrapper2.ge(GasStationinfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeStart().trim());
			
			}
			
			if (!StringUtils.isEmpty(gasStationinfoForecast.getCreateTimeEnd())) {
				queryWrapper2.le(GasStationinfoForecastEntity::getTime,gasStationinfoForecast.getCreateTimeEnd().trim());
				
			}

			List<GasStationinfoForecastEntity> list1 = gasStationinfoForecastService.list(queryWrapper2);
			if(TsBqUtils.isNotNull(list1)){
				
				BigDecimal forecastValueDecimal1 = new BigDecimal(0);
				BigDecimal amountDecimal = new BigDecimal(0);
				
				for (GasStationinfoForecastEntity _gasStationinfoForecast : list1) {
					String forecast = "0";
					String forecastValue1 = _gasStationinfoForecast.getForecastValue1();
					String forecastValue = _gasStationinfoForecast.getForecastValue();
					
					if(TsBqUtils.isNotNull(forecastValue1)){
						forecast = forecastValue1;
					}else if(TsBqUtils.isNotNull(forecastValue)){
						
						if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
								&& !"0".equals(gasLocation)) {
							BigDecimal forecastValueBd = new BigDecimal(forecastValue);
							
							BigDecimal divide = forecastValueBd.divide(new BigDecimal(gasCoverage), 2,
									BigDecimal.ROUND_HALF_UP);
							forecastValueDecimal = divide.multiply(new BigDecimal(gasLocation));
							
							forecast = forecastValueDecimal.toString();

						}else{
							forecast = forecastValue;
							
						}
						
					}
					
					BigDecimal _forecastValue = new BigDecimal(forecast);
					forecastValueDecimal1 = forecastValueDecimal1.add(_forecastValue);
					
					
					String amountDiesel = _gasStationinfoForecast.getAmountDiesel();
					String amountGasoline = _gasStationinfoForecast.getAmountGasoline();
					if(TsBqUtils.isNotNull(amountDiesel)){
						BigDecimal _amountDecimal = new BigDecimal(amountDiesel);
						amountDecimal = amountDecimal.add(_amountDecimal);
					}
					
					if(TsBqUtils.isNotNull(amountGasoline)){
						BigDecimal _amountDecimal = new BigDecimal(amountGasoline);
						amountDecimal = amountDecimal.add(_amountDecimal);
					}
					
					
				}
				gasStationinfoEntity.setForecastValue1(forecastValueDecimal1.toString());
				
				gasStationinfoEntity.setAmount(amountDecimal.toString());
			}
		}
		
		
		if (records.size() > 0) {

			List<GasStationinfoForecastExcel> gasStationinfoForecastExcelList = new ArrayList<>();

			for (GasStationinfoEntity entity : records) {
				String forecastValue1 = "";
				if(TsBqUtils.isNull(entity.getForecastValue1())){
					forecastValue1 = entity.getForecastValue();
				}else{
					forecastValue1 = entity.getForecastValue1();
				}
				
				
				String offlineTime = entity.getOfflineTime(); // 示例字符串
		        BigDecimal number = new BigDecimal(offlineTime);
		        BigDecimal divisor = BigDecimal.valueOf(60);
		        // 除法运算，保留两位小数
		        BigDecimal result = number.divide(divisor, 2, BigDecimal.ROUND_HALF_UP);
		        // 转换为字符串
		        offlineTime = result.toString();
				
				GasStationinfoForecastExcel gasStationinfoForecastExcel = 
						GasStationinfoForecastExcel.builder()
						.id(entity.getId())
						.name(entity.getName())
						.gatherValue(entity.getGatherValue())
						.forecastValue1(forecastValue1)
						.amount(entity.getAmount())
						.offlineTime(offlineTime)
						.taxorgName(entity.getTaxorgName())
						.taxpayerCode(entity.getTaxpayerCode())
						.build();

				gasStationinfoForecastExcelList.add(gasStationinfoForecastExcel);

			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, GasStationinfoForecastExcel.class);
				sheet1.setSheetName("数据");
				writer.write(gasStationinfoForecastExcelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);


				gasMineExportEntity.setFileName(fileName);
				gasMineExportEntity.setUrl(fileUrl + "/" + fileName);
				gasMineExportEntity.setSize(excelFile.length() + "");
				gasMineExportEntity.setState("2");
				gasMineExportEntity.setDescription("导出成功！");
				gasMineExportEntity.setUpdateTime(new Date());
				
				gasMineExportService.updateById(gasMineExportEntity);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				// return DataResult.fail("xlsx生成失败：" + e.toString());
				gasMineExportEntity.setState("2");
				gasMineExportEntity.setDescription("xlsx生成失败：" + e.toString());
				gasMineExportEntity.setUpdateTime(new Date());
				gasMineExportService.updateById(gasMineExportEntity);
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					/// return DataResult.fail("xlsx生成失败：" + e.toString());
					gasMineExportEntity.setState("2");
					gasMineExportEntity.setDescription("xlsx生成失败：" + e.toString());
					gasMineExportEntity.setUpdateTime(new Date());
					gasMineExportService.updateById(gasMineExportEntity);
				}

			}

		} else {
			// return DataResult.fail("暂无加油站停留数据！");
			gasMineExportEntity.setState("2");
			gasMineExportEntity.setDescription("暂无加油站停留数据！");
			gasMineExportEntity.setUpdateTime(new Date());
			gasMineExportService.updateById(gasMineExportEntity);
		}
		
		
		
	}
	
	
	
	public static int daysBetween(Date date1, Date date2) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);
		return Integer.parseInt(String.valueOf(between_days));
	}

}
